package com.ushahidi.android.app;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.ushahidi.android.app.data.DeploymentProvider;
import com.ushahidi.android.app.data.EventDataProvider;
import com.ushahidi.android.app.data.IncidentsData;
import com.ushahidi.android.app.data.UshahidiDatabase;
import com.ushahidi.android.app.util.Util;

public class IncidentSearch extends DashboardActivity
{
    private TextView             mTextView;

    private ListView             mListView;
    
    private Bundle incidentsBundle = new Bundle();
    
    private ListIncidentAdapter ila;
    
    private List<IncidentsData> mOldIncidents;

    private static final int     MENU_SEARCH     = 1;
    
    private static final int VIEW_INCIDENT = 3;

    private final CharSequence[] items           = { "50", "100", "250", "500",
	    "750", "1000", "1500"               };

    private static final int     DIALOG_DISTANCE = 0;

    protected void onCreate(Bundle savedInstanceState)
    {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.deployment_search);
	setTitleFromActivityLabel(R.id.title_text);
    mOldIncidents = new ArrayList<IncidentsData>();
	mTextView = (TextView) findViewById(R.id.search_deploy);
	mListView = (ListView) findViewById(R.id.deployment_list);
	ila = new ListIncidentAdapter(this);
	showResults();
	mTextView.addTextChangedListener(new TextWatcher()
	{

	    public void afterTextChanged(Editable arg0)
	    {
		// TODO Auto-generated method stub

	    }

	    public void beforeTextChanged(CharSequence s, int start, int count,
		    int after)
	    {
		// TODO Auto-generated method stub

	    }

	    public void onTextChanged(CharSequence s, int start, int before,
		    int count)
	    {

		Cursor cursor = showResults(mTextView.getText().toString());

		// Specify the columns we want to display in the result
		String[] from = new String[] {
		        UshahidiDatabase.INCIDENT_TITLE,
		        UshahidiDatabase.INCIDENT_CATEGORIES,
		        UshahidiDatabase.INCIDENT_DESC };

		// Specify the corresponding layout elements where we want the
		// columns to go
		int[] to = new int[] { R.id.deploy_name, R.id.deploy_desc,
		        R.id.deploy_url };

		// Create a simple cursor adapter for the details of the
		// deployment and apply
		// them to the ListView
		if (cursor != null)
		{
		    //SimpleCursorAdapter incidents = new SimpleCursorAdapter(
			//    IncidentSearch.this,
			//    R.layout.deployment_search_result, cursor, from, to);
		    //mListView.setAdapter(incidents);
		    SetIncidentList(cursor);
	        mListView.setOnItemClickListener(RegisterClickListener());
		    
		}
		else
		{
		    showResults();
		}

	    }

	});

    }
    private OnItemClickListener RegisterClickListener()
    {
    	return new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View view, int positions, long id) {
                
                //It seems pull to refresh list is buggy; The list item position item is by 1 higher
                //TODO Look into fixing this.
                int position = positions;
                
                incidentsBundle.putInt("id", mOldIncidents.get(position).getIncidentId());
                incidentsBundle.putString("title", mOldIncidents.get(position).getIncidentTitle());
                incidentsBundle.putString("desc", mOldIncidents.get(position).getIncidentDesc());
                incidentsBundle.putString("longitude", mOldIncidents.get(position)
                        .getIncidentLocLongitude());
                incidentsBundle.putString("latitude", mOldIncidents.get(position)
                        .getIncidentLocLatitude());
                incidentsBundle.putString("category", mOldIncidents.get(position)
                        .getIncidentCategories());
                incidentsBundle.putString("location", mOldIncidents.get(position)
                        .getIncidentLocation());
                incidentsBundle.putString("date", mOldIncidents.get(position).getIncidentDate());
                incidentsBundle.putString("media", mOldIncidents.get(position)
                        .getIncidentThumbnail());
                incidentsBundle.putString("image", mOldIncidents.get(position).getIncidentImage());
                incidentsBundle.putString("status", ""
                        + mOldIncidents.get(position).getIncidentVerified());

                Intent intent = new Intent(IncidentSearch.this, ViewIncidents.class);
                intent.putExtra("incidents", incidentsBundle);
                startActivityForResult(intent, VIEW_INCIDENT);
                setResult(RESULT_OK, intent);

            }
    };
    }
	private void SetIncidentList(Cursor cursor) {
        String title;
        String status;
        String date;
        String description;
        String location;
        String categories;
        String media;
        String image;
        
        String thumbnails[];
        Drawable d = null;

        if (cursor.moveToFirst()) {
            int idIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_ID);
            int titleIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_TITLE);
            int dateIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_DATE);
            int verifiedIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_VERIFIED);
            int locationIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_LOC_NAME);

            int descIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_DESC);

            int categoryIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_CATEGORIES);

            int mediaIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_MEDIA);

            int imageIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_IMAGE);

            int latitudeIndex = cursor
                    .getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_LOC_LATITUDE);

            int longitudeIndex = cursor
                    .getColumnIndexOrThrow(UshahidiDatabase.INCIDENT_LOC_LONGITUDE);

            ila.removeItems();
            ila.notifyDataSetChanged();

            mOldIncidents.clear();

            do {

                IncidentsData incidentData = new IncidentsData();
                mOldIncidents.add(incidentData);
                ListIncidentText listText = new ListIncidentText();

                int id = Util.toInt(cursor.getString(idIndex));
                incidentData.setIncidentId(id);
                incidentData.setIncidentLocLatitude(cursor.getString(latitudeIndex));
                incidentData.setIncidentLocLongitude(cursor.getString(longitudeIndex));

                title = cursor.getString(titleIndex);
                incidentData.setIncidentTitle(title);
                listText.setTitle(Util.capitalize(title));

                description = cursor.getString(descIndex);
                incidentData.setIncidentDesc(description);
                listText.setDesc(description);

                categories = cursor.getString(categoryIndex);
                incidentData.setIncidentCategories(categories);
                listText.setCategories(Util.capitalize(categories));

                location = cursor.getString(locationIndex);
                incidentData.setIncidentLocation(location);
                listText.setLocation(Util.capitalize(location));

                date = Util.formatDate("yyyy-MM-dd HH:mm:ss", cursor.getString(dateIndex),
                        "MMMM dd, yyyy 'at' hh:mm:ss aaa");

                incidentData.setIncidentDate(date);
                listText.setDate(date);

                media = cursor.getString(mediaIndex);
                incidentData.setIncidentThumbnail(media);
                listText.setMedia(media);

                thumbnails = media.split(",");
                // TODO do a proper check for thumbnails
                if (!TextUtils.isEmpty(thumbnails[0])) {
                    d = ImageManager.getImages(thumbnails[0]);        
                } else {
                    d = null;
                }

                listText.setThumbnail(d == null ? getResources().getDrawable(
                        R.drawable.ushahidi_report_icon) : d);

                image = cursor.getString(imageIndex);
                incidentData.setIncidentImage(image);

                status = Util.toInt(cursor.getString(verifiedIndex)) == 0 ? getString(R.string.report_unverified)
                        : getString(R.string.report_verified);
                incidentData.setIncidentVerified(Util.toInt(cursor.getString(verifiedIndex)));
                listText.setStatus(status);

                listText.setId(id);
                listText.setArrow(getResources().getDrawable(R.drawable.ushahidi_arrow));
                ila.addItem(listText);

            } while (cursor.moveToNext());
        }

        cursor.close();
        ila.notifyDataSetChanged();
        mListView.setAdapter(ila);
		
	}
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
	menu.add(0, MENU_SEARCH, 0, R.string.search_label)
	        .setIcon(android.R.drawable.ic_search_category_default)
	        .setAlphabeticShortcut(SearchManager.MENU_KEY);

	return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
	switch (item.getItemId())
	{
	    case MENU_SEARCH:
		onSearchRequested();
		return true;
	}
	return super.onOptionsItemSelected(item);
    }

    /**
     * Searches the dictionary and displays results for the given query.
     * 
     * @param query
     *            The search query
     */
    private Cursor showResults(String query)
    {

	Cursor cursor = managedQuery(EventDataProvider.CONTENT_URI, null,
	        null, new String[] { query }, null);

	return cursor;
    }

    /**
     * Searches the dictionary and displays results for the given query.
     * 
     * @param query
     *            The search query
     */
    private void showResults()
    {

	Cursor cursor = UshahidiApplication.mDb.fetchAllIncidents();

	if (cursor != null)
	{
		/*
	    // There are no results

	    // Specify the columns we want to display in the result
	    String[] from = new String[] { UshahidiDatabase.INCIDENT_TITLE,
		    UshahidiDatabase.INCIDENT_CATEGORIES,
		    UshahidiDatabase.INCIDENT_DESC };

	    // Specify the corresponding layout elements where we want the
	    // columns to go
	    int[] to = new int[] { R.id.deployment_list_name,
		    R.id.deployment_list_desc, R.id.deployment_list_url };

	    // Create a simple cursor adapter for the definitions and apply them
	    // to the ListView
	    SimpleCursorAdapter incidents = new SimpleCursorAdapter(this,
		    R.layout.deployment_list, cursor, from, to);*/
	    SetIncidentList(cursor);
        mListView.setOnItemClickListener(RegisterClickListener());
	}
    }

    /**
     * Create an alert dialog
     */

    protected void createDialog(int d)
    {
	switch (d)
	{
	    case DIALOG_DISTANCE:
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select distance in km");
		builder.setItems(items, new DialogInterface.OnClickListener()
		{
		    public void onClick(DialogInterface dialog, int item)
		    {

		    }
		});

		AlertDialog alert = builder.create();
		alert.show();
	}

    }

    /**
     * Do something when the refresh icon is pressed
     */
    @Override
    public void onRefreshReports(View v)
    {
	createDialog(DIALOG_DISTANCE);
    }

}
